import { Module } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { TypeOrmModule } from '@nestjs/typeorm'
import { LoggerOptions } from 'typeorm'

import { ConfigKeyPaths, IDatabaseReadConfig, IDatabaseWriteConfig } from '~/config'
import { env } from '~/global/env'

import { EntityExistConstraint } from './constraints/entity-exist.constraint'
import { UniqueConstraint } from './constraints/unique.constraint'
import { TypeORMLogger } from './typeorm-logger'
import { AuroraReadWriteService } from './aurora-read-write.service'

// 实体
import { Agent } from '../../agents/entities/agent.entity'
import { Job } from '../../jobs/entities/job.entity'

const providers = [EntityExistConstraint, UniqueConstraint, AuroraReadWriteService]

@Module({
  imports: [
    // 主数据库连接 (写)
    TypeOrmModule.forRootAsync({
      name: 'default', // 默认连接用于写操作
      inject: [ConfigService],
      useFactory: (configService: ConfigService<ConfigKeyPaths>) => {
        const loggerOptions = getLoggerOptions()
        const dbReadConfig = configService.get<IDatabaseWriteConfig>('database_write')

        return {
          ...dbReadConfig,
          name: 'default',
          autoLoadEntities: true,
          logging: loggerOptions,
          logger: new TypeORMLogger(loggerOptions),
          
          // Aurora V2 连接池配置 (写操作)
          extra: {
            max: parseInt(env('DB_WRITER_POOL_MAX') || '8'),     // 写连接池较大
            min: parseInt(env('DB_WRITER_POOL_MIN') || '2'),     // 保持最小连接
            
            // Aurora V2 超时配置
            connectionTimeoutMillis: 30000,
            idleTimeoutMillis: 60000,           // 写连接保持更长时间
            acquireTimeoutMillis: 25000,
            
            // Aurora 特定配置
            keepAlive: true,
            keepAliveInitialDelayMillis: 10000,
            
            // SSL 配置 (Aurora 强制要求)
            ssl: {
              rejectUnauthorized: false,
            },
            
            // Aurora 连接优化
            statement_timeout: 30000,
            query_timeout: 30000,
            
            // 错误处理
            poolErrorHandler: (error: any) => {
              console.error('🚨 写库连接池错误:', error.message);
            },
          },
          
          // TypeORM 配置
          retryAttempts: 5,
          retryDelay: 3000,
          connectTimeoutMS: 30000,
          synchronize: false,
          migrationsRun: env('NODE_ENV') !== 'production',
          entities: [Agent, Job],
        }
      },
    }),

    // 读库连接配置
    TypeOrmModule.forRootAsync({
      name: 'reader', // 只读连接
      inject: [ConfigService],
      useFactory: (configService: ConfigService<ConfigKeyPaths>) => {
        const loggerOptions = getLoggerOptions()
        const dbConfig = configService.get<IDatabaseReadConfig>('database_read')

        return {
          ...dbConfig,
          name: 'reader',
          autoLoadEntities: true,
          logging: loggerOptions,
          logger: new TypeORMLogger(loggerOptions),
          
          // Aurora 读库配置
          host: env('DB_READER_HOST') || env('DB_READER_ENDPOINT'),
          port: parseInt(env('DB_READER_PORT') || '5432'),
          
          // Aurora V2 读库连接池配置
          extra: {
            max: parseInt(env('DB_READER_POOL_MAX') || '15'),    // 读连接池更大
            min: parseInt(env('DB_READER_POOL_MIN') || '3'),     // 更多最小连接
            
            // 读库超时配置
            connectionTimeoutMillis: 30000,
            idleTimeoutMillis: 30000,           // 读连接更快释放
            acquireTimeoutMillis: 20000,
            
            // Aurora 读库优化
            keepAlive: true,
            keepAliveInitialDelayMillis: 5000,
            
            // SSL 配置
            ssl: {
              rejectUnauthorized: false
            },
            
            // 读库特定优化
            statement_timeout: 60000,           // 读查询允许更长时间
            query_timeout: 60000,
            application_name: 'app_reader',     // 便于监控识别
            
            // 只读配置
            default_transaction_read_only: true,
            
            poolErrorHandler: (error: any) => {
              console.error('🚨 读库连接池错误:', error.message);
            },
          },
          
          retryAttempts: 3,                     // 读库重试次数较少
          retryDelay: 2000,
          connectTimeoutMS: 30000,
          synchronize: false,                   // 读库绝不同步
          migrationsRun: false,                 // 读库不运行迁移
        }
      },
    }),
  ],
  providers,
  exports: providers,
})
export class DatabaseModule {}

// 辅助函数：获取日志配置
function getLoggerOptions(): LoggerOptions {
  let loggerOptions: LoggerOptions = ['error', 'warn']
  const dbLogging = env('DB_LOGGING')
  
  if (dbLogging) {
    try {
      loggerOptions = JSON.parse(dbLogging as string)
    } catch {
      loggerOptions = dbLogging as LoggerOptions
    }
  }
  
  return loggerOptions
}